#!/bin/bash

if test -z "$1"; then
    echo "apk file is null. usage: apkdecomplier xxx.apk"
    exit -1
fi
file_relative_path_name=${1}

if test ! -f "$file_relative_path_name"; then
    echo "$file_relative_path_name is not found."
    exit -1
fi


file_relative_path=${file_relative_path_name%/*}

if [[ "$file_relative_path" != "$file_relative_path_name" ]];then
    echo "file_relative_path is: $file_relative_path, cd into it"
    cd $file_relative_path
else
    echo "$file_relative_path_name is in current path: $(pwd)"
fi

file_absolute_path=$(pwd)


file_full_name=${file_relative_path_name##*/}
file_name=${file_full_name%.*}

echo "file path is: $file_absolute_path"
echo "file full name is: $file_full_name"
echo "file name is: $file_name"

apktool d $file_full_name

if test ! -d "$file_name"; then
    echo "decompiler failed. $file_name dir not found"
    exit -1
fi

apktool b $file_name

if test ! -d $file_name/build/apk; then
    echo "apktool b failed. ./build/apk dir not found"
    exit -1
fi

cd $file_name/build/apk

d2j-dex2jar classes.dex

if test -f "classes-dex2jar.jar"; then
    echo "decompiler success! the jar file is $file_name.jar"
    mv classes-dex2jar.jar $file_absolute_path/$file_name.jar
else
    echo "decompiler failed. the classes-dex2jar.jar not found"
fi